package com.hnkj.caiyunweather.ui.place

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.hnkj.caiyunweather.R
import com.hnkj.caiyunweather.databinding.PlaceItemBinding
import com.hnkj.caiyunweather.logic.model.Place
import com.hnkj.caiyunweather.ui.weather.WeatherActivity

class PlaceAdapter(private val fragment:PlaceFragment, private val places:List<Place>)
    :RecyclerView.Adapter<PlaceAdapter.ViewHolder>(){

    inner class ViewHolder(placeItemBinding: PlaceItemBinding) : RecyclerView.ViewHolder(placeItemBinding.root) {
        val placeName: TextView = placeItemBinding.placeName
        val placeAddress: TextView = placeItemBinding.placeAddress
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val holder = ViewHolder( PlaceItemBinding.inflate(LayoutInflater.from(parent.context),parent,false))
        holder.itemView.setOnClickListener {
            val position = holder.adapterPosition
            val place = places[position]
            val activity = fragment.activity
            if(activity is WeatherActivity){
                activity.binding.drawerLayout.closeDrawers()
                activity.viewModel.locationLng = place.location.lng
                activity.viewModel.locationLat = place.location.lat
                activity.viewModel.placeName = place.name
                activity.refreshWeather()
            }else{
                val intent = Intent(parent.context,WeatherActivity::class.java).apply {
                    putExtra("location_lng",place.location.lng)
                    putExtra("location_lat",place.location.lat)
                    putExtra("place_name",place.name)
                }
                fragment.startActivity(intent)
                fragment.activity?.finish()
            }
            fragment.viewmodel.savePlace(place)
        }
        return holder
    }

    override fun getItemCount() = places.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place = places[position]
        holder.placeName.text = place.name
        holder.placeAddress.text = place.address
    }
}